package com.hz.pay.center.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.hz.pay.center.service.IPayNotifyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class NotifyController {


    private Logger logger = LoggerFactory.getLogger(NotifyController.class);


    @Autowired
    private IPayNotifyService payNotifyService;



    /**
     * 支付回调
     * http://paycenter.free.idcfengye.com/pay/result
     * 接收银行或者支付公司的支付结果
     */
    @RequestMapping(value = "/pay/result",method = RequestMethod.POST)
    public String  recivePayResult(HttpServletRequest request){
        //request获取支付宝支付完成后，通知的参数
        // 1.获取回调参数：request
        //         k = v

        Map<String,String> params = new HashMap<String,String>();

        Map<String,String[]> requestParams = request.getParameterMap();

        logger.info("requestParams = " + requestParams.get("name"));


        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("UnsupportedEncodingException",e);
                return "fail";
            }

            params.put(name, valueStr);
        }

        logger.info("#########接收银行或者支付公司的异步回调，回调参数：{}#########",params);

        return payNotifyService.notify(params);


    }

}
